package epimarket.manager;

import java.io.Serializable;
import java.util.ArrayList;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import epimarket.beans.Compte;
import epimarket.helper.DBConnect;
import epimarket.helper.DBQuery;
import epimarket.helper.DBRequest;
import epimarket.helper.Utils;

@ManagedBean
@SessionScoped
public class Login implements Serializable {
	private static final long serialVersionUID = 2L;
	
	private String mail;
	private String mdp;
	private Compte account;
	
	public Login() {
		account = new Compte();
	}
	
	public String connexion() {
		DBConnect db = new DBConnect();
		DBQuery<Compte> dbq = new DBQuery<Compte>();
		DBRequest<Compte> dbr = new DBRequest<Compte>(db, account);
		ArrayList<Compte> list = dbr.select(dbq.where_eq("mail", mail).where_eq("mdp", mdp).all(account));

		if (list.size() == 0) {
			FacesMessage message = new FacesMessage("Authentification failed");
			FacesContext.getCurrentInstance().addMessage( null, message );
			mail = "";
			mdp = "";
			return "error";
		} else {
			account = list.get(0);
			FacesMessage message = new FacesMessage("Authentification success");
			FacesContext.getCurrentInstance().addMessage( null, message );
			return "index";
		}
	}
	
	public boolean isLoggedIn() {
        return (account == null || account.getId() != -1);
    }
	
	public String deconnexion() {
		if (account.getId() != -1) {
			mail = "";
			mdp = "";
			account = new Compte();
		}
		return "index";
	}
	
	public Compte getAccount() {
		return account;
	}
	
	public String getMail() {
		return mail;
	}

	public void setMail(String str) {
		mail = str;
	}
	
	public String getMdp() {
		return mdp;
	}
	
	public void setMdp(String str) {
		mdp = Utils.sha1(str);
	}
}
